from flask import Flask, url_for, redirect, request
from urllib.parse import urlparse, urljoin
from jinja2.utils import generate_lorem_ipsum

app = Flask(__name__)


@app.route('/')
def index():
    return "<h1>index page</h1>"


@app.route('/foo')
def foo():
    return '<h3>Foo Page</h3><a href="%s">Do Something</a>' % url_for('do_sth', next=request.full_path)


@app.route('/bar')
def bar():
    return '<h3>Bar Page</h3><a href="%s">Do Something</a>' % url_for('do_sth', next=request.full_path)


# 视图函数处理完一些事情后，返回原页面，而不是固定的一个首页
@app.route('/dosth')
def do_sth():
    # 1.使用HTTP referer获取上一个页面的URL
    # last_page = request.referrer  # 正确拼写
    # print('----> in do_sth(), last page: ', last_page)
    # resp = redirect(last_page or url_for('index'))  # 有时referrer为空

    # 2. 在访问的URL中增加包含上一个页面URL的参数, 在来源页面设置
    resp = redirect_back()

    # 固定重定向到某个URL
    # resp = redirect(url_for('index'))

    return resp


def redirect_back(default='index', **kwargs):
    for target in request.args.get('next'), request.referrer:
        if not target:
            continue
        if is_safe_url(target):
            print(target)
            return redirect(target)
    return redirect(url_for(default, **kwargs))


# 对URL进行安全验证
def is_safe_url(target):
    ref_url = urlparse(request.host_url)
    test_url = urlparse(urljoin(request.host_url, target))
    print(ref_url)
    print(test_url)
    return test_url.scheme in ('http', 'https') and ref_url.netloc == test_url.netloc

# ajax, 异步加载长文章示例
@app.route('/post')
def show_post():
    post_body = generate_lorem_ipsum(n=2)  # 生成2段随机广西
    return '''
<h1>A very long post</h1>
<div class="body">%s</div>
<button id="load">Load More</button>
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script type="text/javascript">
$(function(){
    $('#load').click(function(){
        $.ajax({
            url: '/more',
            type: 'get',
            success: function(data){
                $('.body').append(data);
            }
        })
    })
})
</script>''' % post_body


@app.route('/more')
def load_post():
    return generate_lorem_ipsum(n=1)
